from rest_framework import serializers
from django.contrib.auth.models import User, Group
from .models import (
    Host, HostGroup, HostType, ConnectionRecord, CommandLog, Alert, UserProfile, UserGroup, UserRole, UserGroupRole,
    MenuItem, GroupMenuPermission, SSHSession, SSHCommand, SSHReplayData, AuditRule, AuditAlert,
    Role, GroupRole, RoleMenuPermission
)
from django.conf import settings
from django.urls import get_script_prefix
from django.core.files.storage import default_storage


class UserProfileSerializer(serializers.ModelSerializer):
    """用户资料序列化器"""
    class Meta:
        model = UserProfile
        fields = ['chinese_name', 'avatar']


class UserSerializer(serializers.ModelSerializer):
    """用户序列化器"""
    chinese_name = serializers.CharField(source='profile.chinese_name', required=False, allow_null=True, allow_blank=True)
    avatar = serializers.ImageField(source='profile.avatar', required=False, allow_null=True)
    avatar_url = serializers.SerializerMethodField()
    groups = serializers.SerializerMethodField()

    class Meta:
        model = User
        fields = ['id', 'username', 'email', 'first_name', 'last_name', 'chinese_name', 'avatar', 'avatar_url', 'is_staff', 'is_active', 'is_superuser', 'date_joined', 'last_login', 'groups']
        read_only_fields = ['id', 'date_joined', 'last_login', 'avatar_url']

    def get_avatar_url(self, obj):
        if hasattr(obj, 'profile') and obj.profile.avatar:
            request = self.context.get('request')
            if request is not None:
                # 使用相对URL，让前端根据当前域名访问
                # 这样可以避免域名/IP变化导致的头像访问问题
                return obj.profile.avatar.url
            return obj.profile.avatar.url
        return None

    def get_groups(self, obj):
        """获取用户所属的自定义用户组"""
        # 优化：检查是否已经预取了相关数据
        if hasattr(obj, '_prefetched_groups'):
            return obj._prefetched_groups

        from .models import UserGroupRole
        user_group_roles = UserGroupRole.objects.filter(user=obj).select_related('group')
        groups = [{'id': ugr.group.id, 'name': ugr.group.name, 'code': ugr.group.code} for ugr in user_group_roles]

        # 缓存结果避免重复查询
        obj._prefetched_groups = groups
        return groups

    def create(self, validated_data):
        """创建用户和关联的profile"""
        # 提取profile数据
        profile_data = validated_data.pop('profile', {})

        # 创建用户
        user = User.objects.create(**validated_data)

        # 确保用户有profile
        if not hasattr(user, 'profile'):
            from .models import UserProfile
            UserProfile.objects.create(user=user)

        # 更新profile数据
        if profile_data:
            for attr, value in profile_data.items():
                setattr(user.profile, attr, value)
            user.profile.save()

        return user

    def update(self, instance, validated_data):
        profile_data = validated_data.pop('profile', {})
        # 更新User模型字段
        for attr, value in validated_data.items():
            setattr(instance, attr, value)
        instance.save()

        # 更新Profile模型字段
        if profile_data and hasattr(instance, 'profile'):
            if 'chinese_name' in profile_data:
                instance.profile.chinese_name = profile_data['chinese_name']
            if 'avatar' in profile_data:
                instance.profile.avatar = profile_data['avatar']
            instance.profile.save()

        return instance


class RegisterSerializer(serializers.ModelSerializer):
    """用户注册序列化器"""
    password = serializers.CharField(write_only=True, required=True, style={'input_type': 'password'})
    password_confirm = serializers.CharField(write_only=True, required=True, style={'input_type': 'password'})
    chinese_name = serializers.CharField(required=False, allow_blank=True)

    class Meta:
        model = User
        fields = ['username', 'email', 'password', 'password_confirm', 'first_name', 'last_name', 'chinese_name']
        extra_kwargs = {
            'first_name': {'required': False},
            'last_name': {'required': False},
            'email': {'required': True}
        }

    def validate(self, data):
        # 检查密码是否匹配
        if data['password'] != data['password_confirm']:
            raise serializers.ValidationError("两次输入的密码不匹配")
        return data

    def create(self, validated_data):
        try:
            # 移除确认密码字段
            validated_data.pop('password_confirm')
            # 提取中文名
            chinese_name = validated_data.pop('chinese_name', '')

            print(f"创建用户, 数据: {validated_data}")

            # 创建用户
            user = User.objects.create_user(
                username=validated_data['username'],
                email=validated_data['email'],
                password=validated_data['password'],
                first_name=validated_data.get('first_name', ''),
                last_name=validated_data.get('last_name', '')
            )

            print(f"用户创建成功: {user.username}, ID: {user.id}")

            # 确保UserProfile已创建
            if not hasattr(user, 'profile'):
                from .models import UserProfile
                UserProfile.objects.create(user=user)
                print(f"为用户 {user.username} 创建了新的 UserProfile")

            # 设置中文名
            if chinese_name:
                user.profile.chinese_name = chinese_name
                user.profile.save()
                print(f"为用户 {user.username} 设置了中文名: {chinese_name}")

            return user
        except Exception as e:
            print(f"创建用户过程中发生错误: {str(e)}")
            raise serializers.ValidationError(f"创建用户失败: {str(e)}")


class HostTypeSerializer(serializers.ModelSerializer):
    """主机类型序列化器"""

    class Meta:
        model = HostType
        fields = '__all__'

    def validate_name(self, value):
        """验证类型名称"""
        if not value.isalnum():
            raise serializers.ValidationError("类型名称只能包含字母和数字")
        return value

    def validate_color(self, value):
        """验证颜色格式"""
        import re
        if not re.match(r'^#[0-9A-Fa-f]{6}$', value):
            raise serializers.ValidationError("颜色必须是有效的十六进制格式，如：#409eff")
        return value

    def validate_icon(self, value):
        """验证图标格式"""
        if not value.startswith('fa-'):
            raise serializers.ValidationError("图标必须是FontAwesome格式，如：fa-server")
        return value

    def validate(self, data):
        """验证整体数据"""
        # 如果是更新操作且为系统内置类型，限制某些字段的修改
        if self.instance and self.instance.is_system:
            # 系统内置类型不能修改名称和is_system字段
            if 'name' in data and data['name'] != self.instance.name:
                raise serializers.ValidationError("系统内置类型不能修改名称")
            if 'is_system' in data and data['is_system'] != self.instance.is_system:
                raise serializers.ValidationError("不能修改系统内置标识")
        return data


class HostGroupSerializer(serializers.ModelSerializer):
    """主机组序列化器"""
    host_count = serializers.ReadOnlyField()
    online_host_count = serializers.ReadOnlyField()
    owner_name = serializers.CharField(source='owner.username', read_only=True)
    owner_chinese_name = serializers.SerializerMethodField()
    environment_display = serializers.CharField(source='get_environment_display', read_only=True)
    hosts = serializers.SerializerMethodField()

    def get_owner_chinese_name(self, obj):
        """安全获取负责人中文名"""
        if obj.owner:
            # 优先从profile获取中文名
            if hasattr(obj.owner, 'profile') and obj.owner.profile and obj.owner.profile.chinese_name:
                return obj.owner.profile.chinese_name
            # 如果没有profile，尝试从用户的first_name和last_name组合
            if obj.owner.first_name or obj.owner.last_name:
                return f"{obj.owner.last_name}{obj.owner.first_name}".strip()
            # 最后返回用户名
            return obj.owner.username
        return None

    class Meta:
        model = HostGroup
        fields = [
            'id', 'name', 'ansible_name', 'description', 'environment', 'environment_display',
            'owner', 'owner_name', 'owner_chinese_name', 'tags', 'is_active',
            'host_count', 'online_host_count', 'hosts', 'created_at', 'updated_at'
        ]
        read_only_fields = ['id', 'created_at', 'updated_at', 'host_count', 'online_host_count']

    def get_hosts(self, obj):
        """获取主机组下的主机列表（简化信息）"""
        hosts = obj.hosts.all()
        return [
            {
                'id': host.id,
                'hostname': host.hostname,
                'public_ip': host.public_ip,
                'private_ip': host.private_ip,
                'status': host.status,
                'type': host.type
            }
            for host in hosts
        ]

    def validate(self, data):
        """自定义验证：在同一环境下主机组名称唯一"""
        name = data.get('name')
        environment = data.get('environment')

        if name and environment:
            # 构建查询条件
            queryset = HostGroup.objects.filter(name=name, environment=environment)

            # 如果是更新操作，排除当前实例
            if self.instance:
                queryset = queryset.exclude(pk=self.instance.pk)

            # 检查是否存在重复
            if queryset.exists():
                env_names = {
                    'dev': '开发环境',
                    'test': '测试环境',
                    'staging': '预发布环境',
                    'prod': '生产环境'
                }
                env_name = env_names.get(environment, environment)
                raise serializers.ValidationError({
                    'name': f'在{env_name}中已存在同名主机组，请使用其他名称'
                })

        return data


class HostSerializer(serializers.Serializer):
    """主机序列化器 - 使用Serializer避免Django 5.x兼容性问题"""
    id = serializers.IntegerField(read_only=True)
    hostname = serializers.CharField(max_length=255, required=False, allow_blank=True)
    ip = serializers.CharField(required=False, allow_null=True, allow_blank=True)
    public_ip = serializers.CharField(required=True)
    private_ip = serializers.CharField(required=False, allow_null=True, allow_blank=True)
    port = serializers.IntegerField(default=22)
    username = serializers.CharField(max_length=255)
    auth_type = serializers.CharField(max_length=20, default='password')
    password = serializers.CharField(write_only=True, required=False, allow_blank=True)
    private_key = serializers.CharField(write_only=True, required=False, allow_blank=True)
    passphrase = serializers.CharField(write_only=True, required=False, allow_blank=True)
    type = serializers.CharField(max_length=50, required=False, allow_blank=True)
    status = serializers.CharField(max_length=20, default='active')
    cpu = serializers.CharField(max_length=255, required=False, allow_blank=True)
    memory = serializers.CharField(max_length=255, required=False, allow_blank=True)
    disk = serializers.CharField(max_length=255, required=False, allow_blank=True)
    os = serializers.CharField(max_length=255, required=False, allow_blank=True)
    cpu_info = serializers.CharField(required=False, allow_blank=True)
    memory_info = serializers.CharField(required=False, allow_blank=True)
    disk_info = serializers.CharField(required=False, allow_blank=True)
    os_version = serializers.CharField(max_length=255, required=False, allow_blank=True)
    system_type = serializers.CharField(max_length=50, required=False, allow_null=True, allow_blank=True)
    cpu_arch = serializers.CharField(max_length=50, required=False, allow_null=True, allow_blank=True)
    system_environment = serializers.CharField(max_length=50, required=False, allow_null=True, allow_blank=True)
    remark = serializers.CharField(required=False, allow_blank=True)
    host_groups = serializers.PrimaryKeyRelatedField(many=True, queryset=HostGroup.objects.all(), required=False)
    host_group_names = serializers.SerializerMethodField()
    created_at = serializers.DateTimeField(read_only=True)
    updated_at = serializers.DateTimeField(read_only=True)

    def get_host_group_names(self, obj):
        """获取主机组名称列表"""
        if hasattr(obj, 'host_groups'):
            return [group.name for group in obj.host_groups.all()]
        return []

    def create(self, validated_data):
        import logging
        logger = logging.getLogger(__name__)

        # 记录创建主机时的数据
        # logger.info(f"创建主机，传入数据: {validated_data}")  # 注释掉避免终端输出干扰

        # 如果没有提供public_ip但提供了ip，则使用ip的值
        if 'ip' in validated_data and 'public_ip' not in validated_data:
            validated_data['public_ip'] = validated_data['ip']

        # 如果cpu_info等为空但旧字段有值，则使用旧字段的值
        if not validated_data.get('cpu_info') and validated_data.get('cpu'):
            validated_data['cpu_info'] = validated_data['cpu']
        if not validated_data.get('memory_info') and validated_data.get('memory'):
            validated_data['memory_info'] = validated_data['memory']
        if not validated_data.get('disk_info') and validated_data.get('disk'):
            validated_data['disk_info'] = validated_data['disk']
        if not validated_data.get('os_version') and validated_data.get('os'):
            validated_data['os_version'] = validated_data['os']

        # 记录处理后的数据
        logger.info(f"处理后的数据: {validated_data}")

        # 确保private_ip为空字符串时转为None
        if 'private_ip' in validated_data and (not validated_data['private_ip'] or
                                              validated_data['private_ip'] == '' or
                                              validated_data['private_ip'] == 'null' or
                                              validated_data['private_ip'] == 'None'):
            logger.info(f"将空的private_ip转换为None")
            validated_data['private_ip'] = None

        # 处理主机组字段（多对多关系）
        host_groups = validated_data.pop('host_groups', None)
        logger.info(f"提取的主机组: {[group.name for group in host_groups] if host_groups else '无'}")

        # 创建主机对象
        host = Host.objects.create(**validated_data)

        # 设置主机组关联（在创建主机后）
        if host_groups is not None:
            host.host_groups.set(host_groups)
            logger.info(f"设置主机组关联: {[group.name for group in host_groups]}")

        # logger.info(f"主机 {host.id} 创建完成")  # 注释掉避免终端输出干扰

        # 异步获取主机详细信息
        try:
            from .tasks import auto_detect_enhanced_host_info
            import threading

            # 在后台线程中执行信息获取，避免阻塞API响应
            def fetch_info():
                try:
                    result = auto_detect_enhanced_host_info(host.id)
                    # logger.info(f"主机 {host.hostname} 信息获取结果: {result}")  # 注释掉避免终端输出干扰
                except Exception as e:
                    logger.error(f"获取主机 {host.hostname} 信息失败: {e}")

            # 延迟3秒后开始获取信息，给主机创建一些时间
            timer = threading.Timer(3.0, fetch_info)
            timer.start()

        except Exception as e:
            logger.warning(f"启动主机信息获取任务失败: {e}")

        return host

    def update(self, instance, validated_data):
        import logging
        logger = logging.getLogger(__name__)

        try:
            # 记录更新主机时的数据（隐藏敏感信息）
            safe_data = {k: v if k not in ['password', 'private_key', 'passphrase'] else '***' for k, v in validated_data.items()}
            logger.info(f"更新主机 {instance.id}，传入数据: {safe_data}")

            # 检查密码字段是否存在
            if 'password' in validated_data:
                logger.info(f"密码字段存在，长度: {len(validated_data['password']) if validated_data['password'] else 0}")
            else:
                logger.info("密码字段不存在于validated_data中")

            # 如果没有提供public_ip但提供了ip，则使用ip的值
            if 'ip' in validated_data and 'public_ip' not in validated_data:
                validated_data['public_ip'] = validated_data['ip']

            # 如果cpu_info等为空但旧字段有值，则使用旧字段的值
            if not validated_data.get('cpu_info') and validated_data.get('cpu'):
                validated_data['cpu_info'] = validated_data['cpu']
            if not validated_data.get('memory_info') and validated_data.get('memory'):
                validated_data['memory_info'] = validated_data['memory']
            if not validated_data.get('disk_info') and validated_data.get('disk'):
                validated_data['disk_info'] = validated_data['disk']
            if not validated_data.get('os_version') and validated_data.get('os'):
                validated_data['os_version'] = validated_data['os']

            # 确保private_ip为空字符串时转为None
            if 'private_ip' in validated_data and (not validated_data['private_ip'] or
                                                  validated_data['private_ip'] == '' or
                                                  validated_data['private_ip'] == 'null' or
                                                  validated_data['private_ip'] == 'None'):
                logger.info(f"将空的private_ip转换为None")
                validated_data['private_ip'] = None

            # 处理密码字段 - 只有用户明确输入了新密码才更新
            if 'password' in validated_data:
                password = validated_data['password']
                if password and password.strip():  # 用户输入了非空密码
                    logger.info("用户输入了新密码，将更新密码")
                    # 保留password字段，让它正常更新
                else:  # 用户没有输入密码或输入了空字符串
                    logger.info("用户没有输入密码，保持原密码不变")
                    validated_data.pop('password')  # 移除空密码字段，保持原密码不变

            # 处理私钥字段
            if 'private_key' in validated_data:
                if not validated_data['private_key']:
                    logger.info("私钥为空，保持原私钥不变")
                    validated_data.pop('private_key')
                else:
                    logger.info("更新私钥")

            # 处理私钥密码字段
            if 'passphrase' in validated_data:
                if not validated_data['passphrase']:
                    logger.info("私钥密码为空，保持原私钥密码不变")
                    validated_data.pop('passphrase')
                else:
                    logger.info("更新私钥密码")

            # 处理主机组字段（多对多关系）
            host_groups = validated_data.pop('host_groups', None)

            # 记录处理后的数据（隐藏敏感信息）
            safe_processed_data = {k: v if k not in ['password', 'private_key', 'passphrase'] else '***' for k, v in validated_data.items()}
            logger.info(f"处理后的数据: {safe_processed_data}")

            for attr, value in validated_data.items():
                setattr(instance, attr, value)
            instance.save()

            # 处理主机组关联（在保存实例后）
            if host_groups is not None:
                instance.host_groups.set(host_groups)
                logger.info(f"更新主机组关联: {[group.name for group in host_groups]}")

            logger.info(f"主机 {instance.id} 更新完成")
            return instance

        except Exception as e:
            logger.error(f"更新主机 {instance.id} 时发生错误: {str(e)}")
            logger.error(f"错误类型: {type(e).__name__}")
            import traceback
            logger.error(f"错误堆栈: {traceback.format_exc()}")
            raise


class ConnectionRecordSerializer(serializers.ModelSerializer):
    """连接记录序列化器"""
    user = UserSerializer(read_only=True)
    host = HostSerializer(read_only=True)
    host_id = serializers.PrimaryKeyRelatedField(queryset=Host.objects.all(), write_only=True, source='host')

    class Meta:
        model = ConnectionRecord
        fields = ['id', 'user', 'host', 'host_id', 'connected_at', 'disconnected_at', 'is_active', 'command_count']
        read_only_fields = ['id', 'user', 'connected_at', 'disconnected_at', 'command_count']

    def create(self, validated_data):
        validated_data['user'] = self.context['request'].user
        return super().create(validated_data)


class CommandLogSerializer(serializers.ModelSerializer):
    """命令日志序列化器"""
    connection = ConnectionRecordSerializer(read_only=True)
    connection_id = serializers.PrimaryKeyRelatedField(queryset=ConnectionRecord.objects.all(), write_only=True, source='connection')

    class Meta:
        model = CommandLog
        fields = ['id', 'connection', 'connection_id', 'command', 'output', 'executed_at']
        read_only_fields = ['id', 'executed_at']


class AlertSerializer(serializers.ModelSerializer):
    """告警序列化器"""
    host = HostSerializer(read_only=True)
    host_id = serializers.PrimaryKeyRelatedField(queryset=Host.objects.all(), write_only=True, source='host')

    class Meta:
        model = Alert
        fields = ['id', 'host', 'host_id', 'title', 'content', 'level', 'is_read', 'created_at']
        read_only_fields = ['id', 'created_at']


class ChangePasswordSerializer(serializers.Serializer):
    """修改密码序列化器"""
    old_password = serializers.CharField(required=True, write_only=True)
    new_password = serializers.CharField(required=True, write_only=True)

    def validate_old_password(self, value):
        user = self.context['request'].user
        if not user.check_password(value):
            raise serializers.ValidationError("原密码不正确")
        return value

    def validate_new_password(self, value):
        if len(value) < 6:
            raise serializers.ValidationError("新密码长度必须至少为6个字符")
        return value


class UserGroupSerializer(serializers.ModelSerializer):
    """用户组序列化器"""
    class Meta:
        model = UserGroup
        fields = ['id', 'name', 'code', 'description', 'created_at', 'updated_at']
        read_only_fields = ['id', 'created_at', 'updated_at']


class SimpleUserRoleSerializer(serializers.ModelSerializer):
    """简单角色序列化器，不包含组信息"""
    level_display = serializers.CharField(source='get_level_display', read_only=True)

    class Meta:
        model = UserRole
        fields = ['id', 'name', 'level', 'level_display', 'description']
        read_only_fields = ['id']


class UserRoleSerializer(serializers.ModelSerializer):
    """用户角色序列化器"""
    group_name = serializers.CharField(source='group.name', read_only=True)
    level_display = serializers.CharField(source='get_level_display', read_only=True)

    class Meta:
        model = UserRole
        fields = ['id', 'name', 'group', 'group_name', 'level', 'level_display', 'description', 'created_at', 'updated_at']
        read_only_fields = ['id', 'created_at', 'updated_at']


class UserGroupRoleSerializer(serializers.ModelSerializer):
    """用户-组-角色关联序列化器"""
    username = serializers.CharField(source='user.username', read_only=True)
    user_chinese_name = serializers.SerializerMethodField()
    group_name = serializers.CharField(source='group.name', read_only=True)
    role_name = serializers.CharField(source='role.name', read_only=True)
    role_level = serializers.IntegerField(source='role.level', read_only=True)

    def get_user_chinese_name(self, obj):
        """安全获取用户中文名"""
        if obj.user and hasattr(obj.user, 'profile') and obj.user.profile:
            return obj.user.profile.chinese_name
        return None

    class Meta:
        model = UserGroupRole
        fields = ['id', 'user', 'username', 'user_chinese_name', 'group', 'group_name',
                 'role', 'role_name', 'role_level', 'is_primary', 'created_at', 'updated_at']
        read_only_fields = ['id', 'created_at', 'updated_at']

    def validate(self, data):
        # 确保角色属于所选组
        if 'role' in data and 'group' in data:
            if data['role'].group.id != data['group'].id:
                raise serializers.ValidationError("所选角色必须属于所选组")
        return data


class UserWithGroupsSerializer(UserSerializer):
    """带有组和角色信息的用户序列化器"""
    groups_roles = serializers.SerializerMethodField()

    class Meta(UserSerializer.Meta):
        fields = UserSerializer.Meta.fields + ['groups_roles']

    def get_groups_roles(self, obj):
        group_roles = UserGroupRole.objects.filter(user=obj).select_related('group', 'role')
        return [
            {
                'id': gr.id,
                'group': {
                    'id': gr.group.id,
                    'name': gr.group.name,
                    'code': gr.group.code
                },
                'role': {
                    'id': gr.role.id,
                    'name': gr.role.name,
                    'level': gr.role.level,
                    'level_display': gr.role.get_level_display()
                },
                'is_primary': gr.is_primary
            }
            for gr in group_roles
        ]


class GroupSerializer(serializers.ModelSerializer):
    """用户组序列化器"""
    class Meta:
        model = Group
        fields = ('id', 'name')


class MenuItemSerializer(serializers.ModelSerializer):
    """菜单项序列化器"""
    children = serializers.SerializerMethodField()
    full_path = serializers.SerializerMethodField()

    class Meta:
        model = MenuItem
        fields = ('id', 'name', 'path', 'icon', 'parent', 'order', 'is_enabled', 'children',
                 'sort_weight', 'component_name', 'is_generated', 'description', 'permission_code',
                 'created_at', 'updated_at', 'full_path')

    def get_children(self, obj):
        children = MenuItem.objects.filter(parent=obj, is_enabled=True).order_by('sort_weight', 'order')
        if not children:
            return []
        return MenuItemSerializer(children, many=True).data

    def get_full_path(self, obj):
        return obj.get_full_path()


class DynamicMenuItemSerializer(serializers.ModelSerializer):
    """动态菜单项序列化器 - 用于菜单管理"""
    children = serializers.SerializerMethodField()
    parent_name = serializers.SerializerMethodField()

    class Meta:
        model = MenuItem
        fields = '__all__'

    def get_children(self, obj):
        children = MenuItem.objects.filter(parent=obj).order_by('sort_weight', 'order')
        return DynamicMenuItemSerializer(children, many=True).data

    def get_parent_name(self, obj):
        return obj.parent.name if obj.parent else None


class MenuCreateSerializer(serializers.ModelSerializer):
    """菜单创建序列化器"""
    generate_page = serializers.BooleanField(default=True, write_only=True)
    english_path = serializers.CharField(required=False, write_only=True)
    english_component = serializers.CharField(required=False, write_only=True)

    class Meta:
        model = MenuItem
        fields = ('name', 'icon', 'parent', 'description', 'generate_page', 'english_path', 'english_component')

    def validate_name(self, value):
        """验证菜单名称"""
        if not value or not value.strip():
            raise serializers.ValidationError("菜单名称不能为空")
        return value.strip()

    def create(self, validated_data):
        """创建菜单时自动生成路径和组件名"""
        # 提取额外参数
        generate_page = validated_data.pop('generate_page', True)
        english_path = validated_data.pop('english_path', None)
        english_component = validated_data.pop('english_component', None)

        # 直接生成菜单数据
        name = validated_data['name']
        parent = validated_data.get('parent')
        icon = validated_data.get('icon', 'fa-file')
        description = validated_data.get('description', '')

        # 优先使用前端传来的英文路径和组件名
        if english_path and english_component:
            route_path = english_path
            component_name = english_component
        else:
            # 如果前端没有传，使用后端生成（fallback）
            from .utils.menu_generator import MenuGenerator
            generator = MenuGenerator()
            route_path = generator.generate_route_path(name)
            component_name = generator.generate_component_name(name)

        menu_data = {
            'name': name,
            'path': f'/{route_path}',
            'icon': icon,
            'description': description,
            'parent': parent,
            'component_name': component_name,
            'permission_code': f'{route_path}.view'
        }

        # 计算排序权重
        parent = validated_data.get('parent')
        if parent:
            last_child = MenuItem.objects.filter(parent=parent).order_by('-sort_weight').first()
            sort_weight = (last_child.sort_weight + 1.0) if last_child else 1.0
        else:
            last_menu = MenuItem.objects.filter(parent__isnull=True).order_by('-sort_weight').first()
            sort_weight = (last_menu.sort_weight + 1.0) if last_menu else 1.0

        menu_data['sort_weight'] = sort_weight
        menu_data['is_generated'] = generate_page  # 根据用户选择设置是否生成页面

        return MenuItem.objects.create(**menu_data)


class GroupMenuPermissionSerializer(serializers.ModelSerializer):
    """用户组菜单权限序列化器"""
    menu_item_detail = MenuItemSerializer(source='menu_item', read_only=True)
    group_name = serializers.CharField(source='group.name', read_only=True)

    class Meta:
        model = GroupMenuPermission
        fields = ('id', 'group', 'menu_item', 'created_at', 'group_name', 'menu_item_detail')


# SSH审计相关序列化器
class SSHSessionSerializer(serializers.ModelSerializer):
    """SSH会话序列化器"""
    user_name = serializers.CharField(source='user.username', read_only=True)
    host_name = serializers.CharField(source='host.hostname', read_only=True)
    host_ip = serializers.CharField(source='host.public_ip', read_only=True)
    status_display = serializers.CharField(source='get_status_display', read_only=True)
    duration_display = serializers.SerializerMethodField()
    client_ip = serializers.CharField(allow_blank=True, allow_null=True, required=False)

    class Meta:
        model = SSHSession
        fields = [
            'id', 'session_id', 'user', 'user_name', 'host', 'host_name', 'host_ip',
            'client_ip', 'user_agent', 'status', 'status_display', 'start_time',
            'end_time', 'duration', 'duration_display', 'command_count', 'data_size',
            'log_file_path', 'replay_file_path', 'created_at', 'updated_at'
        ]
        read_only_fields = [
            'id', 'session_id', 'user_name', 'host_name', 'host_ip', 'status_display',
            'duration_display', 'command_count', 'data_size', 'created_at', 'updated_at'
        ]

    def get_duration_display(self, obj):
        """格式化持续时间显示"""
        if obj.duration:
            hours = obj.duration // 3600
            minutes = (obj.duration % 3600) // 60
            seconds = obj.duration % 60
            if hours > 0:
                return f"{hours}小时{minutes}分{seconds}秒"
            elif minutes > 0:
                return f"{minutes}分{seconds}秒"
            else:
                return f"{seconds}秒"
        return "0秒"


class SSHCommandSerializer(serializers.ModelSerializer):
    """SSH命令序列化器"""
    session_info = serializers.SerializerMethodField()
    risk_level_display = serializers.CharField(source='get_risk_level_display', read_only=True)
    command_type_display = serializers.CharField(source='get_command_type_display', read_only=True)

    class Meta:
        model = SSHCommand
        fields = [
            'id', 'session', 'session_info', 'command_type', 'command_type_display',
            'command', 'output', 'timestamp', 'duration', 'exit_code',
            'risk_level', 'risk_level_display', 'is_dangerous', 'working_directory',
            'environment_vars', 'created_at'
        ]
        read_only_fields = [
            'id', 'session_info', 'command_type_display', 'risk_level_display', 'created_at'
        ]

    def get_session_info(self, obj):
        """获取会话信息"""
        return {
            'session_id': obj.session.session_id,
            'user': obj.session.user.username,
            'host': obj.session.host.hostname,
            'host_ip': obj.session.host.public_ip
        }


class SSHReplayDataSerializer(serializers.ModelSerializer):
    """SSH回放数据序列化器"""
    session_info = serializers.SerializerMethodField()

    class Meta:
        model = SSHReplayData
        fields = [
            'id', 'session', 'session_info', 'timestamp', 'data_type', 'data',
            'terminal_width', 'terminal_height', 'created_at'
        ]
        read_only_fields = ['id', 'session_info', 'created_at']

    def get_session_info(self, obj):
        """获取会话信息"""
        return {
            'session_id': obj.session.session_id,
            'user': obj.session.user.username,
            'host': obj.session.host.hostname
        }


class AuditRuleSerializer(serializers.ModelSerializer):
    """审计规则序列化器"""
    rule_type_display = serializers.CharField(source='get_rule_type_display', read_only=True)
    action_display = serializers.CharField(source='get_action_display', read_only=True)
    risk_level_display = serializers.CharField(source='get_risk_level_display', read_only=True)

    class Meta:
        model = AuditRule
        fields = [
            'id', 'name', 'description', 'rule_type', 'rule_type_display',
            'pattern', 'is_regex', 'case_sensitive', 'action', 'action_display',
            'risk_level', 'risk_level_display', 'is_active', 'priority',
            'created_at', 'updated_at'
        ]
        read_only_fields = [
            'id', 'rule_type_display', 'action_display', 'risk_level_display',
            'created_at', 'updated_at'
        ]


class AuditAlertSerializer(serializers.ModelSerializer):
    """审计告警序列化器"""
    session_info = serializers.SerializerMethodField()
    command_info = serializers.SerializerMethodField()
    rule_name = serializers.CharField(source='rule.name', read_only=True)
    status_display = serializers.CharField(source='get_status_display', read_only=True)
    risk_level_display = serializers.CharField(source='get_risk_level_display', read_only=True)
    handler_name = serializers.CharField(source='handler.username', read_only=True)

    class Meta:
        model = AuditAlert
        fields = [
            'id', 'session', 'session_info', 'command', 'command_info', 'rule',
            'rule_name', 'title', 'description', 'risk_level', 'risk_level_display',
            'status', 'status_display', 'handler', 'handler_name', 'handle_time',
            'handle_note', 'created_at'
        ]
        read_only_fields = [
            'id', 'session_info', 'command_info', 'rule_name', 'status_display',
            'risk_level_display', 'handler_name', 'created_at'
        ]

    def get_session_info(self, obj):
        """获取会话信息"""
        return {
            'session_id': obj.session.session_id,
            'user': obj.session.user.username,
            'host': obj.session.host.hostname,
            'host_ip': obj.session.host.public_ip,
            'start_time': obj.session.start_time
        }

    def get_command_info(self, obj):
        """获取命令信息"""
        return {
            'command': obj.command.command,
            'timestamp': obj.command.timestamp,
            'risk_level': obj.command.risk_level,
            'is_dangerous': obj.command.is_dangerous
        }


# ==================== 角色权限系统序列化器 ====================

class RoleSerializer(serializers.ModelSerializer):
    """角色序列化器"""
    permission_count = serializers.SerializerMethodField()
    group_count = serializers.SerializerMethodField()
    groups = serializers.SerializerMethodField()

    class Meta:
        model = Role
        fields = ['id', 'name', 'description', 'is_system', 'permission_count', 'group_count', 'groups', 'created_at', 'updated_at']
        read_only_fields = ['id', 'created_at', 'updated_at', 'permission_count', 'group_count', 'groups']

    def get_permission_count(self, obj):
        """获取角色的权限数量"""
        return RoleMenuPermission.objects.filter(role=obj).count()

    def get_group_count(self, obj):
        """获取使用此角色的用户组数量"""
        return GroupRole.objects.filter(role=obj).count()

    def get_groups(self, obj):
        """获取使用此角色的用户组列表"""
        group_roles = GroupRole.objects.filter(role=obj).select_related('group')
        return [
            {
                'id': gr.group.id,
                'name': gr.group.name
            }
            for gr in group_roles
        ]

    def validate_name(self, value):
        """验证角色名称"""
        if self.instance and self.instance.is_system:
            # 系统预设角色不能修改名称
            if value != self.instance.name:
                raise serializers.ValidationError("系统预设角色不能修改名称")
        return value

    def validate_is_system(self, value):
        """验证系统标识"""
        if self.instance and self.instance.is_system != value:
            raise serializers.ValidationError("不能修改系统预设标识")
        return value


class GroupRoleSerializer(serializers.ModelSerializer):
    """用户组角色关联序列化器"""
    group_name = serializers.CharField(source='group.name', read_only=True)
    role_name = serializers.CharField(source='role.name', read_only=True)
    role_description = serializers.CharField(source='role.description', read_only=True)

    class Meta:
        model = GroupRole
        fields = ['id', 'group', 'role', 'group_name', 'role_name', 'role_description', 'created_at']
        read_only_fields = ['id', 'created_at']


class RoleMenuPermissionSerializer(serializers.ModelSerializer):
    """角色菜单权限序列化器"""
    role_name = serializers.CharField(source='role.name', read_only=True)
    menu_name = serializers.CharField(source='menu_item.name', read_only=True)
    menu_path = serializers.CharField(source='menu_item.path', read_only=True)
    menu_icon = serializers.CharField(source='menu_item.icon', read_only=True)

    class Meta:
        model = RoleMenuPermission
        fields = [
            'id', 'role', 'menu_item', 'can_read', 'can_write',
            'role_name', 'menu_name', 'menu_path', 'menu_icon', 'created_at'
        ]
        read_only_fields = ['id', 'created_at']


class MenuPermissionTreeSerializer(serializers.ModelSerializer):
    """菜单权限树序列化器"""
    children = serializers.SerializerMethodField()
    permissions = serializers.SerializerMethodField()

    class Meta:
        model = MenuItem
        fields = ['id', 'name', 'path', 'icon', 'order', 'children', 'permissions']

    def get_children(self, obj):
        """获取子菜单"""
        children = MenuItem.objects.filter(parent=obj, is_enabled=True).order_by('order')
        return MenuPermissionTreeSerializer(children, many=True, context=self.context).data

    def get_permissions(self, obj):
        """获取当前角色对此菜单的权限"""
        role_id = self.context.get('role_id')
        if role_id:
            try:
                perm = RoleMenuPermission.objects.get(role_id=role_id, menu_item=obj)
                return {
                    'can_read': perm.can_read,
                    'can_write': perm.can_write
                }
            except RoleMenuPermission.DoesNotExist:
                pass
        return {
            'can_read': False,
            'can_write': False
        }


class GroupWithRolesSerializer(serializers.ModelSerializer):
    """带角色信息的用户组序列化器"""
    roles = serializers.SerializerMethodField()
    user_count = serializers.SerializerMethodField()

    class Meta:
        model = Group
        fields = ['id', 'name', 'roles', 'user_count']

    def get_roles(self, obj):
        """获取用户组的角色列表"""
        group_roles = GroupRole.objects.filter(group=obj).select_related('role')
        return [
            {
                'id': gr.role.id,
                'name': gr.role.name,
                'description': gr.role.description,
                'is_system': gr.role.is_system
            }
            for gr in group_roles
        ]

    def get_user_count(self, obj):
        """获取用户组的用户数量"""
        return obj.user_set.count()
